//
//  DelayTool.m
//  DevDemo
//
//  Created by BO ZHOU on 2021/5/6.
//

#import "DelayTool.h"

static double delayExecuteTime = 0;



@implementation DelayTool


+ (TaskData *)delayWithTime:(double)time task:(VoidBlock)task {
    
    delayExecuteTime = time;
    
    __block VoidBlock delayBlock = task;
    
    __block Task result = nil;
    
    Task delayFinalBlock = ^(bool cancel){
        
        if (delayBlock) {
            if (cancel == false) {
                
                delayBlock();
            }
        }
        
        delayBlock = nil;
        result = nil;
    };
    
    result = delayFinalBlock;
    
    
    [self dispatchLaterWithBlock:^{
        if (result) {
            result(false);
        }
    }];
    
    
    TaskData* taskdata = TaskData.new;
    taskdata.task = result;
    return taskdata;
}

+(void)dispatchLaterWithBlock:(void(^)(void))block {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayExecuteTime * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if (block) {
            block();
        }
    });
}

@end
